const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const connectDB = require('./config/db');
const userRoutes = require('./router/UserRouter');

const app = new Koa();

// 日志记录中间件
app.use(async (ctx, next) => {
    const start = Date.now(); // 记录请求开始时间

    // 输出请求信息
    console.log(`[Request] IP => ${ctx.request.ip}, Method => ${ctx.method}, URL => ${ctx.url}`);

    await next(); // 继续处理下一个中间件

    const duration = Date.now() - start; // 计算请求处理时间

    // 输出响应信息
    console.log(`[Response] Status => ${ctx.status}, Duration => ${duration}ms`);
});


// 连接数据库
connectDB();

// 中间件
app.use(bodyParser());

// 路由
app.use(userRoutes.routes()).use(userRoutes.allowedMethods());

module.exports = app;
